﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Windows;

namespace Vtron.HipcConfigurationTools.Core
{
    /// <summary>
    /// Socket 消息处理类
    /// </summary>
    public class SocketHandler
    {
        /// <summary>
        /// Socket 消息处理
        /// </summary>
        /// <typeparam name="T">应答类型</typeparam>
        /// <param name="request">请求类</param>
        /// <param name="ip">请求Ip</param>
        /// <param name="port">请求端口</param>
        /// <returns>应答类</returns>
        public T Handle<T>(object request, string ip, int port) where T : new()
        {
            T response = new T();
            byte[] Message = Utils.StructToBytes(request);
            TcpClient socket = new TcpClient();

            IPAddress ipAddress = IPAddress.Parse(ip);
            socket.Connect(ipAddress, port);
            NetworkStream ns = socket.GetStream();
            ns.Write(Message, 0, Message.Length);
            ns.ReadTimeout = 3000;
            byte[] Recv = new byte[1024];
            List<byte> newRecv = new List<byte>();
            try
            {
                do
                {
                    ns.Read(Recv, 0, Recv.Length);
                    newRecv.AddRange(Recv);
                }
                while (ns.DataAvailable);
                byte[] resultRecv = newRecv.ToArray();
                response = (T)Utils.BytesToStruct(resultRecv, typeof(T));
            }
            finally
            {
                socket.Close();
                ns.Close();
            }

            return response;
        }

        /// <summary>
        /// Socket 消息处理
        /// </summary>
        /// <typeparam name="T">应答类型</typeparam>
        /// <param name="request">请求类</param>
        /// <returns>应答类</returns>
        public T Handle<T>(object request) where T : new()
        {
            return Handle<T>(request, Utils.IP, Utils.PORT);
        }

        /// <summary>
        /// Socket 消息异步处理
        /// </summary>
        /// <typeparam name="T">应答类型</typeparam>
        /// <param name="request">请求类</param>
        /// <param name="endHandle">应答结束委托</param>
        public void BeginHandle<T>(object request, Action<T> endHandle)
        {
            byte[] Message = Utils.StructToBytes(request);
            TcpClient socket = new TcpClient();
            socket.BeginConnect(Utils.IP, Utils.PORT, (IAsyncResult ar) =>
            {
                T response;
                NetworkStream ns = socket.GetStream();
                ns.Write(Message, 0, Message.Length);
                byte[] Recv = new byte[1024];
                int NumberOfRecv = 0;
                IList<byte> newRecv = new List<byte>();
                ns.ReadTimeout = 3000;
                try
                {
                    do
                    {
                        NumberOfRecv = ns.Read(Recv, 0, Recv.Length);
                        for (int i = 0; i < NumberOfRecv; i++)
                        {
                            newRecv.Add(Recv[i]);
                        }
                    }
                    while (ns.DataAvailable);
                    byte[] resultRecv = new byte[newRecv.Count];
                    newRecv.CopyTo(resultRecv, 0);

                    response = (T)Utils.BytesToStruct(resultRecv, typeof(T));
                    socket.Close();
                    ns.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                endHandle(response);
            }, null);
        }
    }
}
